import {
	getCache,
	setCache,
	removeCache
} from "@/utils/cache";

import defaultAvatar from '@/assets/img/default_avatar.jpg';

const state = {
	logged: getCache('access_token') != null,
	userInfo: JSON.parse(getCache('userInfo')),
	userId: getCache('userId')
}

const getters = {
	isLogin: state => {
		return state.logged;
	},
    nick: state => {
        if (state.userInfo == null) {
            return "登录";
        }
        return state.userInfo.userNick;
    },
    avatar: state => {
        if (state.userInfo == null) {
            return defaultAvatar;
        }
        return state.userInfo.poster;
    }
}

const mutations = {
	login: (state, tokenInfo) => {
		setCache('access_token', tokenInfo.access_token);
		setCache('refresh_token', tokenInfo.refresh_token);
		setCache('expires_at', tokenInfo.expires_at);
	},
	setUserInfo: (state, userInfo) => {
		setCache('userInfo', JSON.stringify(userInfo));
		setCache('userId', userInfo.id);
		state.userInfo = userInfo;
		state.userId = userInfo.id;
		state.logged = true;
	},
	logout: state => {
		state.logged = false;
		state.userInfo = null;
		state.userId = null;
		removeCache('access_token');
		removeCache('refresh_token');
		removeCache('expires_at');
		removeCache('userInfo');
		removeCache('userId');
	}
}

const actions = {}

export default {
	namespaced: true,
	state,
	getters,
	actions,
	mutations
}
